//
//  WYMapController.m
//  Boss
//
//  Created by admin on 2018/6/1.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "WYMapController.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "WYCustomAnnotationView.h"
#import "WYDismantlingController.h"
#import "WYBaseNavigationController.h"
#import "WYLocationHelper.h"
#import "WYLeftBarButtonItem.h"
#import "WYRightBarButtonItem.h"
#import "WYMyRedPacketController.h"
#import "AnimatedAnnotationView.h"
#import "WYPointAnnotation.h"
#import "WYScanerAnnotation.h"
#import "WYScannerAnnotationView.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import "WYLoginController.h"
#import "WYNearRedPacket.h"
#import "WYRedPacketMessageController.h"
#import "UINavigationController+WXSTransition.h"
#import "WYTaskController.h"
#import "WYShareController.h"
#import "WYStrategyController.h"
#import "WYExclusiveAnnotaiton.h"
#import "WYExclusiveModel.h"
#import "WYMessageController.h"
#import "WYExclusiveController.h"
#import <AVFoundation/AVFoundation.h>
#import "WYUserMessage.h"
#import "WYStartModel.h"
#import "XHLaunchAdManager.h"
#import "WYNewViewController.h"
#import "UIButton+Badge.h"
#import "WYHeroController.h"
#import "WYMessageListController.h"
#import "WYHeroRank.h"
#import "WYHeroAlertController.h"
#define kCalloutViewMargin          -8
@interface WYMapController ()<MAMapViewDelegate,AVAudioPlayerDelegate>
{
    NSUInteger test;
   
    
    
}
@property (nonatomic,strong)WYLeftBarButtonItem *leftItem;
@property (nonatomic, strong) MAMapView *mapView;

@property (nonatomic, strong) WYShadowButton *gpsButton;

@property (nonatomic, strong) NSArray *circles;

@property (nonatomic,strong)WYScanerAnnotation *annotation;
@property (nonatomic,strong) AMapLocationManager *locationManager;
@property (nonatomic,strong)NSMutableArray *redpacketArray;

@property (nonatomic,strong) AMapLocationReGeocode *regeocode;
@property (nonatomic,strong)NSMutableArray *annotationArray;

@property (nonatomic,strong)WYDismantlingController *dismantlingVc;

@property (nonatomic,strong)NSMutableArray *pointArray;

@property (nonatomic,strong)NSMutableArray *exclusiveArray;
@property (nonatomic,strong)NSMutableArray *exclusivePointArray;

@property (nonatomic,strong)AVAudioPlayer *musicPlayer;

@property (nonatomic,strong)MACircle *circle;
@property (nonatomic,strong)UIImageView *imageView;
@property (nonatomic,strong)WYRightBarButtonItem *rightBarItem;

@property (nonatomic,strong) WYHeroAlertController *hac1;
@property (nonatomic,strong) WYHeroAlertController *hac2;
@property (nonatomic,strong) WYHeroAlertController *hac3;




@end

@implementation WYMapController
-(NSMutableArray *)exclusiveArray
{
    if (!_exclusiveArray) {
        _exclusiveArray = [[NSMutableArray alloc]init];
    }
    return _exclusiveArray;
}
-(NSMutableArray *)exclusivePointArray
{
    if (!_exclusivePointArray) {
        _exclusivePointArray = [[NSMutableArray alloc]init];
    }
    return _exclusivePointArray;
}

-(NSMutableArray *)pointArray
{
    if (!_pointArray) {
        _pointArray = [[NSMutableArray alloc]init];
    }
    return _pointArray;
}


-(NSMutableArray *)annotationArray
{
    if (!_annotationArray) {
        _annotationArray = [[NSMutableArray alloc]init];
    }
    return _annotationArray;
}
-(NSMutableArray *)redpacketArray
{
    if (!_redpacketArray) {
        _redpacketArray = [[NSMutableArray alloc]init];
    }
    
    
    return _redpacketArray;
}
-(void)sendDay
{
    [WYHttpServer sendDaySucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            
        }
        
    }];
}
-(void)loadMessageCount
{
    WEAKSELF
    [WYHttpServer seeAllUnreadNumberSucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        
        if (success) {
            NSInteger count = [response[@"result"] integerValue];
            if (count>0) {
                if (count>99) {
                    weakSelf.rightBarItem.mesBtn.badgeValue = [NSString stringWithFormat:@"%ld",99];
                    weakSelf.rightBarItem.mesBtn.badgeBGColor = [UIColor redColor];
                }else{
                    weakSelf.rightBarItem.mesBtn.badgeValue = [NSString stringWithFormat:@"%ld",count];
                    weakSelf.rightBarItem.mesBtn.badgeBGColor = [UIColor redColor];
                }
                
            }else{
                weakSelf.rightBarItem.mesBtn.shouldHideBadgeAtZero=YES;
                weakSelf.rightBarItem.mesBtn.badgeValue = @"0";
            }
        }
    }];
}
-(void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
    [self loadUserData];
    NSString *token = [WYStoreModule currentToken];
    if (token.length) {
        [self sendDay];
    }
    [self loadMessageCount];
    [super viewWillAppear:animated];
    [self.mapView setZoomLevel:14.0];
    if (!self.musicPlayer) {
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"radar" ofType:@"mp3"];
        NSURL *fileUrl = [NSURL URLWithString:filePath];
        self.musicPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:nil];
        self.musicPlayer.delegate = self;
        self.musicPlayer.enableRate = YES;
        self.musicPlayer.rate = 1.5;
    }
    if (![self.musicPlayer isPlaying]){
        [self.musicPlayer setVolume:0.6];
        [self.musicPlayer prepareToPlay];
        [self.musicPlayer play];
    }
    
    [self.mapView removeAnnotations:self.annotationArray];
    [self.mapView removeAnnotations:self.pointArray];
    [self.mapView removeAnnotations:self.exclusivePointArray];
    
    
    if (!self.annotation) {
        WYScanerAnnotation *annotation = [[WYScanerAnnotation alloc] init];
        self.annotation = annotation;
        annotation.coordinate =self.mapView.userLocation.coordinate;
        annotation.subtitle = @"CustomAnnotationView";
        [self.mapView addAnnotation:annotation];
    }
    [self addCircle];
    
    WEAKSELF
    int64_t delayInSeconds = 1.8;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf.mapView removeAnnotation:weakSelf.annotation];
        weakSelf.annotation = nil;
    });
    [self sureLocation];
    [self loadCount];
    [self wr_setNavBarBackgroundAlpha:0];
}
-(void)showRefreshView
{
    UIImageView *imageView = [[UIImageView alloc]init];
    self.imageView = imageView;
    [self.view addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.gpsButton.mas_right).offset(0);
        make.centerY.equalTo(self.gpsButton);
    }];
    imageView.image = [UIImage imageNamed:@"refreshFindRedPacket"];
    
    CAKeyframeAnimation *shakeAnim = [CAKeyframeAnimation animation];
    
    shakeAnim.keyPath = @"transform.translation.x";
    
    shakeAnim.duration = 0.8;
    
    CGFloat delta = 10;
    
    shakeAnim.values = @[@10 , @(-delta), @(delta), @10];
    
    shakeAnim.repeatCount = MAXFLOAT;
    
    [imageView.layer addAnimation:shakeAnim forKey:nil];
}
-(void)showNewView
{
    WYNewViewController *nvc = [[WYNewViewController alloc]init];
    nvc.complete = ^{
        WYDismantlingController *dismantlingVc = [[WYDismantlingController alloc]init];
        self.dismantlingVc = dismantlingVc;
        WEAKSELF
        dismantlingVc.exit = ^{
            [weakSelf.dismantlingVc.view removeFromSuperview];
            [weakSelf.maskView removeFromSuperview];
        };
        WYPointAnnotation *annotation = [[WYPointAnnotation alloc]init];
        if (self.pointArray.count) {
            annotation = self.pointArray[0];
            
        }
        dismantlingVc.complte = ^{
            WYRedPacketMessageController *redVc = [[WYRedPacketMessageController alloc]init];
            
            
            
            redVc.redPacket =annotation.redPacket;
            [weakSelf.navigationController pushViewController:redVc animated:YES];
            [weakSelf.dismantlingVc.view removeFromSuperview];
            [weakSelf.maskView removeFromSuperview];
        };
        dismantlingVc.errorComplte = ^(NSString *errorMessage) {
            [weakSelf.dismantlingVc.view removeFromSuperview];
            [weakSelf.maskView removeFromSuperview];
            [weakSelf toast:errorMessage];
            
        };
        dismantlingVc.redMessage = annotation.redPacket;
        [[UIApplication sharedApplication].keyWindow addSubview:self.maskView];
        [[UIApplication sharedApplication].keyWindow addSubview:dismantlingVc.view];
        dismantlingVc.view.frame = self.view.bounds;
        [dismantlingVc setNameString:annotation.redPacket.userName];
        [dismantlingVc setContentString:annotation.redPacket.content];
        //                    if (State) {
        //                        [dismantlingVc setISVip:!State];
        //                    }
        
        dismantlingVc.view.transform = CGAffineTransformMakeScale(0.01f, 0.01f);//将要显示的view按照正常比例显示出来
        [UIView beginAnimations:nil context:UIGraphicsGetCurrentContext()];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];  //InOut 表示进入和出去时都启动动画
        [UIView setAnimationDuration:0.2f];//动画时间
        dismantlingVc.view.transform=CGAffineTransformMakeScale(1.0f, 1.0f);//先让要显示的view最小直至消失
        [UIView commitAnimations]; //启动动画
        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3* NSEC_PER_SEC));
        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        });
        
        
    };
    [[UIApplication sharedApplication].keyWindow addSubview:nvc.view];
    nvc.view.frame = SCREEN_BOUNDS;
    [self addChildViewController:nvc];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self loadStart];
}


-(void)loadData
{
    WEAKSELF
    [WYHttpServer getMyInfoSucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            WYMyInfo *info = [WYMyInfo getMyInfoFromJson:response[@"result"]];
            [WYStoreModule storeMyInfo:info];
        }
    }];
}






-(void) loadStart
{
    [WYHttpServer getStart:nil SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        
            if (success) {
                WYStartModel *model = [WYStartModel getStartModelFromJson:response[@"result"]];
              //  model.enableTime
                 NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                 [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
                
                NSDate *date = [formatter dateFromString:model.enableTime];
                NSInteger inter  = [date compareOneDay:date withAnotherDay:[NSDate date]];
                if (inter>0) {
                    [WYStoreModule storeLastStrat:model];
                }else{
                    if ([model.type isEqualToString:@"1"]) {
                        model.url = [NSString stringWithFormat:@"%@!default",model.url];
                    }
                    [WYStoreModule storeStrat:model];
                    if ([model.type isEqualToString:@"1"]) {
                        [[XHLaunchAdManager shareManager]  batchDownloadImageAndCache];
                    }else{
                       [[XHLaunchAdManager shareManager]  batchDownloadVideoAndCache];
                    }
                }
            }
    }];
}
-(void)loadUserData
{
    WEAKSELF
    [WYHttpServer getUserMessageSucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        
        if (success) {
           WYUserMessage *userMessage = [WYUserMessage getUserMessageFromJson:response[@"result"]];
            
            if (!userMessage.isPush.intValue) {
                [weakSelf loadHeroList];
            }
            
            //[weakSelf updateUI];
            [WYStoreModule storeUserMessage:userMessage];
        }
        
    }];
}
-(void)loadHeroList
{
    WEAKSELF
    [WYHttpServer getHeroPushSucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            STRONGSELF
            WYHeroRank *heroRank = [WYHeroRank getRankWithFromJson:response[@"result"]];
            NSLog(@"%@",heroRank);
            if (heroRank.isSuccess.intValue) {
                
                if (heroRank.HeroList.people) {
                    WYHeroAlertController *hac = [[WYHeroAlertController alloc]init];
                    
                     strongSelf.hac1 = hac;
                    [[UIApplication sharedApplication].keyWindow addSubview:hac.view];
                    hac.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
                   [hac setPeopleRank:heroRank];
                    
                    [weakSelf showannitWithView:hac.view];
                   
                }
                if (heroRank.HeroList.packet) {
                   WYHeroAlertController *hac = [[WYHeroAlertController alloc]init];
                    [[UIApplication sharedApplication].keyWindow addSubview:hac.view];
                    hac.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
                     strongSelf.hac2 = hac;
                    [weakSelf showannitWithView:hac.view];
                    [hac setRedpacktRank:heroRank];
                }
                if (heroRank.HeroList.money) {
                    WYHeroAlertController *hac = [[WYHeroAlertController alloc]init];
                    [[UIApplication sharedApplication].keyWindow addSubview:hac.view];
                    hac.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
                    [weakSelf showannitWithView:hac.view];
                    strongSelf.hac3 = hac;
                    
                     [hac setMoenyRank:heroRank];
                }
            }else{
                WYHeroAlertController *hac = [[WYHeroAlertController alloc]init];
                [[UIApplication sharedApplication].keyWindow addSubview:hac.view];
                hac.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
                [weakSelf showannitWithView:hac.view];
                weakSelf.hac3 = hac;
                [hac setHeroRank:heroRank];
                
                
            }
            
            
            
        }
        
        
        
    }];
    
    
}
-(void)showannitWithView:(UIView *)view
{
    view.transform = CGAffineTransformMakeScale(0.01f, 0.01f);//将要显示的view按照正常比例显示出来
    [UIView beginAnimations:nil context:UIGraphicsGetCurrentContext()];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];  //InOut 表示进入和出去时都启动动画
    [UIView setAnimationDuration:0.2f];//动画时间
    view.transform=CGAffineTransformMakeScale(1.0f, 1.0f);//先让要显示的view最小直至消失
    [UIView commitAnimations]; //启动动画
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3* NSEC_PER_SEC));
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
    });
}



-(void)loadShareList
{
    [self.exclusiveArray removeAllObjects];
    WEAKSELF
    [WYHttpServer getSharePacketListSucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            [weakSelf.exclusiveArray addObjectsFromArray:[WYExclusiveModel gerExclusiveArrayFromJson:response[@"result"]]];
            [weakSelf addExclusivePoint];
            
        }
    }];
}
-(void)addExclusivePoint
{
    WYLocationBean *oldLocationBean = [[WYLocationBean alloc]init];
    oldLocationBean.lat = self.mapView.userLocation.location.coordinate.latitude;
    oldLocationBean.lon = self.mapView.userLocation.location.coordinate.longitude;
    for (WYExclusiveModel *exclusive in self.exclusiveArray) {
            WYLocationBean * newLocationBean =  [WYLocationHelper generateRandomScopeLocation:oldLocationBean];
            CLLocationCoordinate2D randomCoordinate = CLLocationCoordinate2DMake(newLocationBean.lat, newLocationBean.lon);
            WYExclusiveAnnotaiton *annotation = [[WYExclusiveAnnotaiton alloc] init];
            annotation.coordinate = randomCoordinate;
            annotation.subtitle = @"CustomAnnotationView";
            annotation.exclusiveModel = exclusive;
            [self.mapView addAnnotation:annotation];
            [self.exclusivePointArray addObject:annotation];
        }
}

-(void)loadCount
{
    WEAKSELF
    [WYHttpServer getRedPacketCountSucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            [weakSelf.leftItem setLabelText:response[@"result"]];
        }
    }];
}




- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:YES];
    self.tabBarController.tabBar.hidden = NO;
    self.mapView.showsUserLocation = YES;  //self.mapView.customizeUserLocationAccuracyCircleRepresentation = YES;
    self.mapView.userTrackingMode = MAUserTrackingModeNone;
    
    
}
#pragma mark - mapview delegate
-(void)addCircle
{
    if (self.circle) {
        [self.mapView removeOverlay:self.circle];
    }
    MACircle *circle1 = [MACircle circleWithCenterCoordinate:self.mapView.userLocation.location.coordinate radius:1500];
    self.circle = circle1;
    [self.mapView addOverlay:circle1];
}

-(void)addRedImage
{
    WYLocationBean *oldLocationBean = [[WYLocationBean alloc]init];
    oldLocationBean.lat = self.mapView.userLocation.location.coordinate.latitude;
    oldLocationBean.lon = self.mapView.userLocation.location.coordinate.longitude;
    for (WYNearRedPacket *redpacket in self.redpacketArray) {
        if ([redpacket.redpacketType isEqualToString:@"1"]||redpacket.scope.integerValue!=1) {
            WYLocationBean * newLocationBean =  [WYLocationHelper generateRandomScopeLocation:oldLocationBean];
            CLLocationCoordinate2D randomCoordinate = CLLocationCoordinate2DMake(newLocationBean.lat, newLocationBean.lon);
           // [self addAnnotationWithCooordinate:randomCoordinate];
            WYPointAnnotation *annotation = [[WYPointAnnotation alloc] init];
            annotation.coordinate = randomCoordinate;
            annotation.subtitle = @"CustomAnnotationView";
            annotation.isReceived = [redpacket.isReceived integerValue];
            annotation.isReceiveFinished = [redpacket.isReceiveFinished integerValue];
            annotation.userPhoto = redpacket.userPhoto;
            annotation.redPacket = redpacket;
            [self.mapView addAnnotation:annotation];
            [self.annotationArray addObject:annotation];
        }else{
                NSArray *coorArray = [redpacket.coordinate componentsSeparatedByString:@","];
                CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake([coorArray[0] floatValue], [coorArray[1] floatValue]);
                //  [self addAnnotationWithCooordinate:coordinate];
                WYPointAnnotation *annotation = [[WYPointAnnotation alloc] init];
                annotation.coordinate = coordinate;
                annotation.subtitle = @"CustomAnnotationView";
                annotation.isReceived = [redpacket.isReceived integerValue];
                annotation.isReceiveFinished = [redpacket.isReceiveFinished integerValue];
                annotation.userPhoto = redpacket.userPhoto;
                annotation.redPacket = redpacket;
                [self.mapView addAnnotation:annotation];
                [self.pointArray addObject:annotation];
        }
    }
}





-(void)addAnnotationWithCooordinate:(CLLocationCoordinate2D)coordinate
{
    WYPointAnnotation *annotation = [[WYPointAnnotation alloc] init];
    annotation.coordinate = coordinate;
    annotation.subtitle = @"CustomAnnotationView";
    [self.mapView addAnnotation:annotation];
}


-(void)setupUI
{
    ///地图需要v4.5.0及以上版本才必须要打开此选项（v4.5.0以下版本，需要手动配置info.plist）
    [AMapServices sharedServices].enableHTTPS = YES;
    
    ///初始化地图
    MAMapView *_mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
    self.mapView = _mapView;
    self.mapView.showsCompass = NO;
//     self.mapView.centerCoordinate =self.mapView.userLocation.location.coordinate;
    self.mapView.delegate = self;
    ///把地图添加至view
    [self.view addSubview:_mapView];
    [self.mapView setZoomLevel:14.0];
    [self.mapView setMinZoomLevel:14.0];
    self.mapView.cameraDegree = 0;
    self.mapView.rotateCameraEnabled = NO;
    self.gpsButton = [self makeGPSButtonView];
    self.gpsButton.center = CGPointMake(CGRectGetMidX(self.gpsButton.bounds) + 10,self.view.bounds.size.height -  CGRectGetMidY(self.gpsButton.bounds) -88);
    [self.view addSubview:self.gpsButton];
    self.gpsButton.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin;
    UIButton *heroBtn = [[UIButton alloc]init];
    [self.view addSubview:heroBtn];
    
    [heroBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(45);
        make.height.mas_equalTo(40);
        make.right.mas_equalTo(-16);
        make.bottom.mas_equalTo(-88);
    }];
    
    [heroBtn setImage:[UIImage imageNamed:@"hero"] forState:(UIControlStateNormal)];
    
    [heroBtn addTarget:self action:@selector(clickHeroBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    
    
    
    CGFloat top = 20;
    if (kDevice_Is_iPhoneX) {
        top = 44;
    }
   // [self wr_setNavBarBackgroundAlpha:0];
    [self wr_setNavBarShadowImageHidden:YES];
    //self.hbd_barHidden = YES;
    
    [self wr_setStatusBarStyle:UIStatusBarStyleDefault];
    WYLeftBarButtonItem *leftItem = [[WYLeftBarButtonItem alloc]initWithFrame:CGRectMake(15, 64, kScreenWidth/2.3, 44)];
    self.leftItem = leftItem;
    [leftItem.addButton addTarget:self action:@selector(addCountAction) forControlEvents:(UIControlEventTouchUpInside)];
    UIBarButtonItem *leftBarButtonItem  = [[UIBarButtonItem alloc]initWithCustomView:leftItem];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    self.navigationItem.leftBarButtonItem.width = kScreenWidth/2.3;
    WYRightBarButtonItem *rightBarItem = [[WYRightBarButtonItem alloc]initWithFrame:CGRectMake(0, 0, 44*4*DUP+16, 44)];
    self.rightBarItem = rightBarItem;
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightBarItem];
   // rightBarItem.width = 44*3+15;
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    self.navigationItem.rightBarButtonItem.width = 44*4*DUP+15;
    self.navigationItem.title = @"";
    [rightBarItem.redBtn addTarget:self action:@selector(redAction) forControlEvents:UIControlEventTouchUpInside];
    [rightBarItem.shareBtn addTarget:self action:@selector(shareAction) forControlEvents:(UIControlEventTouchUpInside)];
    [rightBarItem.strategyBtn addTarget:self action:@selector(strategyAction) forControlEvents:(UIControlEventTouchUpInside)];
    [rightBarItem.mesBtn addTarget:self action:@selector(messageAction) forControlEvents:UIControlEventTouchUpInside];
    self.mapView.showsScale = NO;
}
-(void)clickHeroBtn:(UIButton *)btn
{
    if (![self isLogin]) {
        return;
    }
    
    WYHeroController *hvc = [[WYHeroController alloc]init];
    [self.navigationController pushViewController:hvc animated:YES];
}
//-(void)loadMessageCount
//{
//    WEAKSELF
//    [WYHttpServer getUnreadNumberSucessBlock:^(BOOL success, id response, NSString *errorMessage) {
//        if (success) {
//            NSInteger count = [response[@"result"] integerValue];
//            if (count>0) {
//                 weakSelf.rightBarItem.mesBtn.badgeValue = @" ";
//                weakSelf.rightBarItem.mesBtn.badgeBGColor = [UIColor orangeColor];
//            }else{
//            weakSelf.rightBarItem.mesBtn.shouldHideBadgeAtZero=YES;
//            weakSelf.rightBarItem.mesBtn.badgeValue = @"0";
//            }
//        }
//    }];
//}
-(void)messageAction
{
    if (![self isLogin]) {
        return;
    }
    WYMessageListController *mvc = [[WYMessageListController alloc]init];
    [self.navigationController pushViewController:mvc animated:YES];
}
-(void)loadNearRedPacket:(CLLocation *)location WithAddress:(AMapLocationReGeocode *)regeocode
{
    NSString *coordinate = [NSString stringWithFormat:@"%f,%f",location.coordinate.latitude,location.coordinate.longitude];
   // [self.redpacketArray removeAllObjects];
   
    
    
   // self.mapView removeOverlay:<#(id<MAOverlay>)#>
    WEAKSELF 
    [WYHttpServer getNearRedPacketWithCoordinate:coordinate WithProvince:regeocode.province WithCity:regeocode.city WithCountry:regeocode.district SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            [weakSelf.redpacketArray removeAllObjects];
            weakSelf.redpacketArray = [[NSMutableArray alloc]initWithArray:[WYNearRedPacket getNearModelFromJson:response[@"result"]]];
            [weakSelf.mapView removeAnnotations:weakSelf.annotationArray];
            [weakSelf.mapView removeAnnotations:weakSelf.pointArray];
            
            
            [weakSelf addRedImage];
            
        }else{
        }
    }];
}
-(void)addCountAction
{
    if (![self isLogin]) {
        return;
    }
    
    
    WYTaskController *tvc = [[WYTaskController alloc]init];
    [self.navigationController pushViewController:tvc animated:YES];
}

-(void)shareAction
{
    if (![self isLogin]) {
        return;
    }
    WYShareController *svc = [[WYShareController alloc]init];
    [self.navigationController pushViewController:svc animated:YES];
}
-(void)strategyAction
{
    if (![self isLogin]) {
        return;
    }
    WYStrategyController *svc = [[WYStrategyController alloc]init];
    [self.navigationController pushViewController:svc animated:YES];
}
-(void)redAction
{
    if (![self isLogin]) {
        return;
    }
    WYMyRedPacketController *mvc = [[WYMyRedPacketController alloc]init];
    [self.navigationController pushViewController:mvc animated:YES];
}
- (WYShadowButton *)makeGPSButtonView {
    WYShadowButton *ret = [[WYShadowButton alloc] initWithFrame:CGRectMake(0, 0, 34, 34)];
    //ret.backgroundColor = [UIColor whiteColor];
    ret.layer.cornerRadius = 4;
    [ret setImage:[UIImage imageNamed:@"icon_location"] forState:UIControlStateNormal];
    [ret addTarget:self action:@selector(gpsAction) forControlEvents:UIControlEventTouchUpInside];
    [ret setBackgroundColor:[UIColor whiteColor]];
    return ret;
}
- (void)gpsAction {
    
    CABasicAnimation* rotationAnimation;
    
    //绕哪个轴，那么就改成什么：这里是绕y轴 ---> transform.rotation.y
    
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    //旋转角度
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI];
    //每次旋转的时间（单位秒）
    rotationAnimation.duration = 0.3;
    rotationAnimation.cumulative = YES;
    //重复旋转的次数，如果你想要无数次，那么设置成MAXFLOAT
    rotationAnimation.repeatCount = 4;
    
    [self.gpsButton.imageView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
    
    
    [self.mapView setZoomLevel:14.0];
    if (!self.musicPlayer) {
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"radar" ofType:@"mp3"];
        NSURL *fileUrl = [NSURL URLWithString:filePath];
        self.musicPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:nil];
        self.musicPlayer.delegate = self;
        self.musicPlayer.enableRate = YES;
        self.musicPlayer.rate = 1.5;
    }
    if (![self.musicPlayer isPlaying]){
        [self.musicPlayer setVolume:0.6];
        [self.musicPlayer prepareToPlay];
        [self.musicPlayer play];
    }
    if(self.mapView.userLocation.updating && self.mapView.userLocation.location) {
        [self.mapView setCenterCoordinate:self.mapView.userLocation.location.coordinate animated:YES];
        [self.gpsButton setSelected:YES];
    }
    [self.mapView setCenterCoordinate:self.mapView.userLocation.location.coordinate];
    [self.mapView removeAnnotations:self.annotationArray];
    [self.mapView removeAnnotations:self.pointArray];
    [self.mapView removeAnnotations:self.exclusivePointArray];
    if (!self.annotation) {
        WYScanerAnnotation *annotation = [[WYScanerAnnotation alloc] init];
        self.annotation = annotation;
        annotation.coordinate =self.mapView.userLocation.coordinate;
        annotation.subtitle = @"CustomAnnotationView";
        [self.mapView addAnnotation:annotation];
    }
    WEAKSELF
    int64_t delayInSeconds = 1.8;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf.mapView removeAnnotation:weakSelf.annotation];
        weakSelf.annotation = nil;
    });
    [self addCircle];
    [self loadNearRedPacket:self.mapView.userLocation.location WithAddress:self.regeocode];
    [self loadShareList];
    [self loadCount];
    
}

#pragma mark AVPlayDelegate
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [self.musicPlayer stop];
    self.musicPlayer=nil;
    self.musicPlayer.delegate = nil;
}



#pragma mark - MAMapViewDelegate
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MACircle class]])
    {
        MACircleRenderer *circleRenderer = [[MACircleRenderer alloc] initWithCircle:overlay];
        
        circleRenderer.lineWidth   = 0.5f;
        circleRenderer.strokeColor = [UIColor hexStringToColor:@"#d8593f" alpha:0.08];
        circleRenderer.fillColor   = [[UIColor hexStringToColor:@"#d8593f" alpha:1.0] colorWithAlphaComponent:0.08];
        return circleRenderer;
    }
    
    return nil;
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAUserLocation class]]) {
       
        MAUserLocationRepresentation *r = [[MAUserLocationRepresentation alloc] init];
        r.showsAccuracyRing = NO;
        r.showsHeadingIndicator = NO;
        r.strokeColor = [UIColor blueColor];
        r.enablePulseAnnimation = YES;
        [mapView updateUserLocationRepresentation:r];
        return nil;
    }
    
    
    
    
    
    
    
    
    
    
    
    if ([annotation isKindOfClass:[WYPointAnnotation class]])
    {
        static NSString *customReuseIndetifier = @"WYPointAnnotation";
        WYCustomAnnotationView *annotationView =     (WYCustomAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[WYCustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier];
            // must set to NO, so we can show the custom callout view.
            annotationView.canShowCallout = NO;
            annotationView.draggable = NO;
            //annotationView.calloutOffset = CGPointMake(0, -5);
        }
        
        WYPointAnnotation *wyAnnotation = (WYPointAnnotation *)annotation;
        if (wyAnnotation.isReceived||wyAnnotation.isReceiveFinished) {
            [annotationView.portraitImageView sd_setImageWithURL:[NSURL URLWithString:wyAnnotation.userPhoto] placeholderImage:nil];
            annotationView.portraitImageView.width = 30;
            annotationView.portraitImageView.height = 30;
            [annotationView.portraitImageView setCornerRadius:15.0f];
            
            
        }else{
            
            annotationView.portraitImageView.width = 32;
            annotationView.portraitImageView.height = 40;
            [annotationView.portraitImageView setCornerRadius:0.0f];
            if (wyAnnotation.redPacket.vipRedpacket.integerValue) {
                if (wyAnnotation.redPacket.vipLevel.integerValue==10) {
                    annotationView.portrait = [UIImage imageNamed:@"vip白银红包"];
                }else if(wyAnnotation.redPacket.vipLevel.integerValue==20){
                    annotationView.portrait = [UIImage imageNamed:@"VIP_redPacket"];
                }else{
                    annotationView.portrait = [UIImage imageNamed:@"home_redPacket_Diamonds"];
                }
                
                
                
            }else{
                 annotationView.portrait = [UIImage imageNamed:@"normal_redPacket"];
            }
            annotationView.zIndex = 99;
            
           
        }
        
    
        
        return annotationView;
    }
    if ([annotation isKindOfClass:[WYExclusiveAnnotaiton class]]) {
        
        static NSString *customReuseIndetifier = @"WYExclusiveAnnotaiton";
        WYCustomAnnotationView *annotationView = (WYCustomAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];
        
        if (annotationView == nil)
        {
            annotationView = [[WYCustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier];
            // must set to NO, so we can show the custom callout view.
            annotationView.canShowCallout = NO;
            annotationView.draggable = NO;
            //annotationView.calloutOffset = CGPointMake(0, -5);
        }
        annotationView.portrait = [UIImage imageNamed:@"exclusive_redPacket"];
        annotationView.portraitImageView.width = 32;
        annotationView.portraitImageView.height = 40;
        annotationView.zIndex = 99;
        return annotationView;
    }
    if ([annotation isKindOfClass:[WYScanerAnnotation class]])
    {
        
        static NSString *customReuseIndetifier = @"WYScanerAnnotation";
        WYScannerAnnotationView *annotationView = (WYScannerAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];
        if (annotationView == nil)
        {
              CGFloat height = 3000.0/self.mapView.metersPerPointForCurrentZoom;
            annotationView = [[WYScannerAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier WithRect:CGRectMake(0, 0, height, height)];
            // must set to NO, so we can show the custom callout view.
            annotationView.canShowCallout = NO;
            annotationView.draggable = NO;
            //annotationView.calloutOffset = CGPointMake(0, -5);
        }
        annotationView.portrait = [UIImage imageNamed:@"scanner"];
        [annotationView start];
        return annotationView;
    }

    return nil;
}

- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view
{
    if (![self isLogin]) {
        return;
    }
    MAMapPoint point1 = MAMapPointForCoordinate(view.annotation.coordinate);
    MAMapPoint point2 = MAMapPointForCoordinate(self.mapView.userLocation.location.coordinate);
    //2.计算距离
    CLLocationDistance distance = MAMetersBetweenMapPoints(point1,point2);
    if (distance>1500) {
        [self toast:@"超出领取范围了哦～亲"];return;
    }
    
    if ([view.annotation isKindOfClass:[WYPointAnnotation class]]) {
        WYDismantlingController *dismantlingVc = [[WYDismantlingController alloc]init];
        self.dismantlingVc = dismantlingVc;
        
        BOOL State = NO;
        
    WYPointAnnotation *annotation = (WYPointAnnotation *)view.annotation;
        if (annotation.redPacket.vipRedpacket.integerValue) {
            WYUserMessage *userMessage = [WYStoreModule currentUserMessage];
 if(userMessage.vipId.integerValue<annotation.redPacket.vipLevel.integerValue) {
                WYRedPacketMessageController *redVc = [[WYRedPacketMessageController alloc]init];
                redVc.redPacket = annotation.redPacket;
                redVc.isCountDown = YES;
                [self.navigationController pushViewController:redVc animated:YES];
                return;
            }else{
                // self.dismantlingVc.vipImageView.hidden = NO;
              //  [self.dismantlingVc setISVip:NO];
                State  =  YES;
            }
        }
        //State  =  YES;
    WEAKSELF
    dismantlingVc.exit = ^{
        [weakSelf.dismantlingVc.view removeFromSuperview];
        [weakSelf.maskView removeFromSuperview];
        };
    dismantlingVc.complte = ^{
        WYRedPacketMessageController *redVc = [[WYRedPacketMessageController alloc]init];
            redVc.redPacket =annotation.redPacket;
            [weakSelf.navigationController pushViewController:redVc animated:YES];
         [weakSelf.dismantlingVc.view removeFromSuperview];
        [weakSelf.maskView removeFromSuperview];
        };
        dismantlingVc.errorComplte = ^(NSString *errorMessage) {
            [weakSelf.dismantlingVc.view removeFromSuperview];
            [weakSelf.maskView removeFromSuperview];
            [weakSelf toast:errorMessage];
            
        };
    
    dismantlingVc.redMessage = annotation.redPacket;
        if (!annotation.isReceiveFinished) {
            if (!annotation.isReceived) {
                [[UIApplication sharedApplication].keyWindow addSubview:self.maskView];
                [[UIApplication sharedApplication].keyWindow addSubview:dismantlingVc.view];
                dismantlingVc.view.frame = self.view.bounds;
                [dismantlingVc setNameString:annotation.redPacket.userName];
                [dismantlingVc setContentString:annotation.redPacket.content];
                if (State) {
                    [dismantlingVc setISVip:!State];
                    if (annotation.redPacket.vipLevel.integerValue==10) {
                        [dismantlingVc setImageView:@"new白银专属"];
                    }
                    if (annotation.redPacket.vipLevel.integerValue==20) {
                        [dismantlingVc setImageView:@"new黄金专属"];
                    }
                    if (annotation.redPacket.vipLevel.integerValue==30) {
                        [dismantlingVc setImageView:@"redPacketMessage_diamonds_exclusive_right"];
                    }
                    
                }
                
                dismantlingVc.view.transform = CGAffineTransformMakeScale(0.01f, 0.01f);//将要显示的view按照正常比例显示出来
                [UIView beginAnimations:nil context:UIGraphicsGetCurrentContext()];
                [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];  //InOut 表示进入和出去时都启动动画
                [UIView setAnimationDuration:0.2f];//动画时间
                dismantlingVc.view.transform=CGAffineTransformMakeScale(1.0f, 1.0f);//先让要显示的view最小直至消失
                [UIView commitAnimations]; //启动动画
                dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3* NSEC_PER_SEC));
                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                });
            }else{
                WYRedPacketMessageController *redVc = [[WYRedPacketMessageController alloc]init];
                redVc.redPacket = annotation.redPacket;
                [self.navigationController pushViewController:redVc animated:YES];
            }
           
        }else{
            
            WYRedPacketMessageController *redVc = [[WYRedPacketMessageController alloc]init];
            redVc.redPacket = annotation.redPacket;
            [self.navigationController pushViewController:redVc animated:YES];
        }
    }
    
    if ([view.annotation isKindOfClass:[WYExclusiveAnnotaiton class]]) {
        WYExclusiveAnnotaiton *annotation = (WYExclusiveAnnotaiton *)view.annotation;
        WYDismantlingController *dismantlingVc = [[WYDismantlingController alloc]init];
        self.dismantlingVc = dismantlingVc;
        dismantlingVc.model =annotation.exclusiveModel;
        WEAKSELF
        dismantlingVc.exit = ^{
            [weakSelf.dismantlingVc.view removeFromSuperview];
            [weakSelf.maskView removeFromSuperview];
        };
        dismantlingVc.complte = ^{
            WYExclusiveController *evc = [[WYExclusiveController alloc]init];
            evc.money = annotation.exclusiveModel.money;
            [weakSelf.navigationController pushViewController:evc animated:YES];
            [weakSelf.dismantlingVc.view removeFromSuperview];
            [weakSelf.maskView removeFromSuperview];
        };
        dismantlingVc.errorComplte = ^(NSString *errorMessage) {
            [weakSelf.dismantlingVc.view removeFromSuperview];
            [weakSelf.maskView removeFromSuperview];
            [weakSelf toast:errorMessage];
        };
        [[UIApplication sharedApplication].keyWindow addSubview:self.maskView];
        [[UIApplication sharedApplication].keyWindow addSubview:dismantlingVc.view];
        dismantlingVc.view.frame = self.view.bounds;
        
        dismantlingVc.isExclusive = YES;
        
        dismantlingVc.view.transform = CGAffineTransformMakeScale(0.01f, 0.01f);//将要显示的view按照正常比例显示出来
        [UIView beginAnimations:nil context:UIGraphicsGetCurrentContext()];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];  //InOut 表示进入和出去时都启动动画
        [UIView setAnimationDuration:0.2f];//动画时间
       dismantlingVc.view.transform=CGAffineTransformMakeScale(1.0f, 1.0f);//先让要显示的view最小直至消失
        [UIView commitAnimations]; //启动动画
        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3* NSEC_PER_SEC));
        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        });
    }
   [mapView deselectAnnotation:view.annotation animated:NO];
}
-(void)mapView:(MAMapView *)mapView didDeselectAnnotationView:(MAAnnotationView *)view
{
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self wr_setNavBarBackgroundAlpha:1];
    
}
#pragma mark 定位
-(void)sureLocation
{
    self.locationManager = [[AMapLocationManager alloc]init];
    // 带逆地理信息的一次定位（返回坐标和地址信息）
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    //   定位超时时间，最低2s，此处设置为2s
    self.locationManager.locationTimeout =2;
    //   逆地理请求超时时间，最低2s，此处设置为2s
    self.locationManager.reGeocodeTimeout = 2;
    WEAKSELF
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (error)
        {
            
            if (error.code == AMapLocationErrorLocateFailed)
            {
                return;
            }
        }
        [weakSelf.mapView setCenterCoordinate:location.coordinate];
        weakSelf.regeocode = regeocode;
        [weakSelf loadNearRedPacket:location WithAddress:regeocode];
        [weakSelf loadShareList];
        [weakSelf addCircle];
        if (regeocode)
        {
            
        }
    }];
}
-(BOOL)isLogin
{
    NSString *token =[WYStoreModule currentToken];
    if (token.length) {
        return YES;
    }else{
        WYLoginController *loginVc = [[WYLoginController alloc] initWithNibName:@"WYLoginController" bundle:nil];
        WYBaseNavigationController *nav = [[WYBaseNavigationController alloc]initWithRootViewController:loginVc];
        [self presentViewController:nav animated:YES completion:nil];
        return NO;
    }
}
@end
